package org.hibiscus.jdp.app.dbdoc.mysql;

import com.deepoove.poi.data.RowRenderData;
import org.hibiscus.jdp.app.dbdoc.DataSource;
import org.hibiscus.jdp.app.dbdoc.DbTypeConstants;
import org.hibiscus.jdp.app.dbdoc.POIFileUtils;
import org.hibiscus.jdp.app.dbdoc.TableStructureDoc;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Description: MySQL数据表结构文档
 *
 * @author 然诺
 * @date 2019/8/12
 */
public class MySQLTableStructureDoc implements TableStructureDoc {

	@Override
	public String createDocument(DataSource dataSource, String outFilePath) {
		// 查询表信息
		String metaInfoSql = "SELECT table_name, table_type , ENGINE,table_collation,table_comment, create_options " +
				"FROM information_schema.TABLES WHERE table_schema='" + dataSource.getTableSchema() + "'";
		// 查询表结构信息
		String structureInfoSql = "SELECT ordinal_position,column_name,column_type, column_key, extra ,is_nullable, column_default, column_comment,data_type,character_maximum_length "
				+ "FROM information_schema.columns WHERE table_schema='" + dataSource.getTableSchema() + "' and table_name='";

		// 获取表元数据
		List<Map<String, String>> metaInfoList = MySqlUtils.getTableStructureData(dataSource, metaInfoSql, true);

		List<Map<String, Object>> tableList = new ArrayList<>();
		int i = 0;
		for (Map<String, String> metaInfo : metaInfoList) {
			String sql = structureInfoSql + metaInfo.get("table_name") + "'";
			List<Map<String, String>> tableStructureData = MySqlUtils.getTableStructureData(dataSource, sql, false);
			if (tableStructureData != null && !tableStructureData.isEmpty()) {
				List<RowRenderData> rowList = POIFileUtils.getRowRenderData(tableStructureData);
				tableList.add(POIFileUtils.mapData(metaInfo, rowList, ++i));
			}
		}

		// 默认生成的文件名
		String fileName = "数据库表结构(MySQL)-" + System.currentTimeMillis() + ".docx";
		// 输出文件
		POIFileUtils.outFile(outFilePath, fileName, tableList, DbTypeConstants.MYSQL);
		return fileName;
	}

}
